package com.sd.sdk.core.utils;


import com.sd.sdk.core.exception.ApiDecryptException;
import com.sd.sdk.core.exception.ApiEncryptException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 加解密工具(非通用工具)
 * @author xy
 */
public class ApiDesEdeUtil {

    private static final String CRYPT_ALGORITHM = "DESede";

    public static SecretKey getKey(String key) {
        return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), CRYPT_ALGORITHM);
    }

    /**
     * 解密
     * @param value
     * @param secretKey
     * @return
     */
    public static String decrypt(String value, SecretKey secretKey) {
        try {
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedByte = cipher.doFinal(ApiUrlBase64Util.decode(value));
            return new String(decryptedByte,StandardCharsets.UTF_8);
        } catch(Exception e) {
            throw new ApiDecryptException("解密异常", e);
        }
    }

    /**
     * 加密
     * @param value
     * @param secretKey
     * @return
     */
    public static String encrypt(String value, SecretKey secretKey) {
        try {
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedByte = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
            return ApiUrlBase64Util.encodeToString(encryptedByte);
        } catch(Exception e) {
            throw new ApiEncryptException("加密异常", e);
        }
    }
}
